<?php
/**
 * Created by PhpStorm.
 * User: zqk
 * Date: 2018/5/16
 * Time: 15:50
 */

namespace Services;

use Helpers\Tool;
use Helpers\Main;
use Helpers\HttpClient;
use Helpers\XhException;

class Box
{

    /**
     * @var \Helpers\HttpClient
     */
    public static $httpClient;
    public static $url;

    /**
     * 初始化盒子信息
     *
     * @throws XhException
     *
     * create by zqk 20180913
     */
    private static function init()
    {
        if (!self::$httpClient) {
            $config = Main::getConfigByName('box');
            self::$url = Tool::getValue($config, 'url'); //box服务地址
            if (!self::$url) {
                throw new XhException('box服务url获取失败');
            }
            self::$httpClient = new HttpClient(self::$url);
        }
    }

    /**
     * 获取box列表
     *
     * @param int $online
     * @param int $type
     * @param int $schoolId
     * @param int $health
     * @param int $start
     * @param int $limit
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by zqk 20180912
     */
    public static function getBox($online = 1, $type = 0, $schoolId = 0, $health = 0, $start = 0, $limit = 20)
    {
        self::init();
        $params = [
            'online' => $online,
            'type' => $type,
            'start' => $start,
            'limit' => $limit,
            'health' => $health,
        ];
        if ($schoolId) {
            $params['schoolId'] = $schoolId;
        }
        $response = self::$httpClient->get("/box/manager/list", $params);
        if (!$response->isSuccess()) {
            throw new XhException('获取Box列表失败', $response);
        }
        $datas = $response->toArray();
        foreach ($datas as $k => $data) {
            $box = $data['box'];
            $actualBox = $data['actualBox'];
            $boxInfo = array_merge($box, $actualBox);
            $arr = [
                'preReceiveRate', 'preTransmitRate', 'highPreReceiveRate', 'highPreTransmitRate', 'lowPreReceiveRate',
                'lowPreTransmitRate', 'avgReceiveRate', 'avgTransmitRate', 'externalDownloadRate',
                'externalDownloadLimitRate', 'downloadingFlow', 'uploadingFlow', 'externalUploadRate',
                'externalUploadLimitRate', 'twoMinuteAvgReceiveRate', 'fiveMinuteAvgReceiveRate',
                'tenMinuteAvgReceiveRate', 'twoMinuteAvgTransmitRate', 'fiveMinuteAvgTransmitRate',
                'tenMinuteAvgTransmitRate'];
            foreach ($boxInfo as $key => $value) {
                if (in_array($key, $arr)) {
                    $boxInfo[$key] = self::formatBytes($value);
                }
                if ($key == 'lastAccessTime') {
                    $boxInfo[$key] = date('Y-m-d H:i:s', ceil($value / 1000));
                }
            }
            $datas[$k] = $boxInfo;
            $datas[$k]['iId'] = $k + 1;
        }
        return $datas;
    }

    /**
     * 获取盒子num
     *
     * @param int $online
     * @param int $type
     * @param int $schoolId
     * @param int $health
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by zqk 20180913
     */
    public static function getBoxNum($online = 1, $type = 0, $schoolId = 0, $health = 0)
    {
        self::init();
        $params = [
            'online' => $online,
            'type' => $type,
            'health' => $health,
            'start' => 0,
        ];
        if ($schoolId) {
            $params['schoolId'] = $schoolId;
        }
        $response = self::$httpClient->get("/box/manager/list", $params);
        if (!$response->isSuccess()) {
            throw new XhException('获取Box数量失败', $response);
        }
        $datas = $response->toArray();
        foreach ($datas as $k => $data) {
            $box = $data['box'];
            $actualBox = $data['actualBox'];
            $boxInfo = array_merge($box, $actualBox);
            $datas[$k] = $boxInfo;
        }
        return $datas;
    }

    /**
     * 修改盒子信息
     *
     * @param $schoolId
     * @param $appId
     * @param $code
     * @param $schoolName
     * @param $drs
     * @param $dfrs
     * @param $ulrs
     * @param $dlrs
     * @param $dbw
     * @param $ubw
     *
     * @return array|bool|mixed|\stdClass
     * @throws \Exception
     *
     * create by zqk 20180913
     */
    public static function updateBox($mac, $schoolId, $appId, $code, $schoolName, $drs, $dfrs, $ulrs, $dlrs, $dbw, $ubw)
    {
        self::init();
        $params = [
            'mac' => $mac,
            'schoolId' => $schoolId,
            'appId' => $appId,
            'code' => $code,
            'schoolName' => $schoolName,
            'downloadReportSwitch' => $drs,
            'downloadFailedReportSwitch' => $dfrs,
            'uploadLimitRateSwitch' => $ulrs,
            'downloadLimitRateSwitch' => $dlrs,
            'downBandwidth' => $dbw,
            'upBandwidth' => $ubw
        ];
        $response = self::$httpClient->post("/box/manager/update", $params);
        return $response->toArray();
    }

    /**
     * 获取盒子下载上报记录列表
     *
     * @param string $mac
     * @param string $url
     * @param int $type
     * @param string $tag
     * @param int $start
     * @param int $limit
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by zqk 20180913
     */
    public static function getBoxFileList($mac = '', $url = '', $type = 0, $tag = '', $start = 0, $limit = 20)
    {
        self::init();
        $params = [
            'mac' => $mac,
            'url' => $url,
            'type' => $type,
            'tag' => $tag,
            'start' => $start,
            'limit' => $limit
        ];
        $response = self::$httpClient->get("/box/manager/boxfile/list", $params);
        if (!$response->isSuccess()) {
            throw new XhException('获取盒子下载上报记录列表失败', $response);
        }
        $data = $response->toArray();
        return $data;
    }

    /**
     * 获取盒子下载失败上报记录列表
     *
     * @param string $mac
     * @param string $url
     * @param int $start
     * @param int $limit
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by zqk 20180913
     */
    public static function getBoxFileErrorList($mac = '', $url = '', $start = 0, $limit = 20)
    {
        self::init();
        $params = [
            'mac' => $mac,
            'url' => $url,
            'start' => $start,
            'limit' => $limit
        ];
        $response = self::$httpClient->get("/box/manager/boxfile/error/list", $params);
        if (!$response->isSuccess()) {
            throw new XhException('获取盒子下载失败上报记录列表失败', $response);
        }
        $data = $response->toArray();
        return $data;
    }

    /**
     * 获取macList
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by zqk 20180913
     */
    public static function getMacList()
    {
        self::init();
        $response = self::$httpClient->get('/box/manager/mac/list');
        if (!$response->isSuccess()) {
            throw new XhException('获取盒子下载失败上报记录列表失败', $response);
        }
        $data = $response->toArray();
        return $data;
    }

    /**
     * B MB GB TB转化
     *
     * @param $size
     *
     * @return string
     *
     * create by zqk 20180918
     */
    public static function formatBytes($size)
    {
        $units = array(' B', ' KB', ' MB', ' GB', ' TB');
        for ($i = 0; $size >= 1024 && $i < 4; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $units[$i];
    }

    /**
     * 根据盒子mac获取盒子状态
     *
     * @param $macId
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181109
     */
    public static function getBoxStatusByMac($macId)
    {
        self::init();
        $response = self::$httpClient->get('/box/manager/ms/session/' . $macId);
        if (!$response->isSuccess()) {
            throw new XhException('接口获取盒子状态出错', $response);
        }
        $data = $response->body;//返回的是字符串
        return $data;
    }

}